<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
// Setting the Content-Type header with charset
//header('Refresh: 60;url=http://localhost/xml.php'); 
header('Content-Type: text/xml; charset=utf-8');
require_once("./utils.php.inc");
require_once("./settings.php.inc");
session_start();

$currentDriverLanguage = isset($_SESSION['currentDriverLanguage'])?$_SESSION['currentDriverLanguage']:DEFAULT_LANG_FOR_DRIVER_INTERFACE;//add logic for cookie read
$_SESSION['currentDriverLanguage']= $currentDriverLanguage;

echo('<?xml version="1.0" encoding="UTF-8"?><Document>');

//--Next station value
$sql = "SET NAMES utf8";
if ( ($result = query_wrapper($sql, __FILE__, __LINE__))==null){
	$error_occured = true;
}
else {
	$sql = 'select nn.node_name, pd.current_route_code, pd.current_node_seq_no from route_schedule_node_assoc rsna , node_names nn , persistent_data pd '
	        . ' WHERE '
	        . ' rsna.route_schedule_code = pd.current_route_code '
	        . ' AND rsna.node_seq_no = ( pd.current_node_seq_no + 1 ) '
	        . ' AND rsna.node_code = nn.node_code '
	        . ' AND nn.lang_code = \''.$currentDriverLanguage.'\' LIMIT 1';
	if ( ($result_ns = query_wrapper($sql, __FILE__, __LINE__))==null){
		$error_occured = true;
	}
	else {
		if (mysql_num_rows($result_ns)==0){
			$sql = 'select nn.node_name, pd.current_route_code, pd.current_node_seq_no from route_schedule_node_assoc rsna , node_names nn , persistent_data pd '
	        . ' WHERE '
	        . ' rsna.route_schedule_code = pd.current_route_code '
	        . ' AND rsna.node_seq_no = ( pd.current_node_seq_no + 1 ) '
	        . ' AND rsna.node_code = nn.node_code '
	        . ' AND nn.lang_code = \''.DEFAULT_LANG_FOR_DRIVER_INTERFACE.'\' LIMIT 1';
			
			if ( ($result_ns = query_wrapper($sql, __FILE__, __LINE__))==null){
				$error_occured = true;
			}
		}
	}

	if(!$error_occured){
		if (mysql_num_rows($result_ns)==0){
			//means last node
			$next_station_value = "";
		}
		else{
			while ($row_ns = mysql_fetch_array($result_ns, MYSQL_ASSOC)) {
				if (strcmp($row_ns["current_node_seq_no"],"-1")==0){
					echo('<NextStation><name></name><distance></distance></NextStation>');
					echo('<FinalDestination><name></name><distance></distance></FinalDestination>');
					echo('<CurrentStation><name></name></CurrentStation>');
					echo('<CurrentRouteCode>---</CurrentRouteCode>');
					echo ('<RouteChanged>false</RouteChanged>');
					echo('</Document>');
					exit();
				}
				$next_station_value = $row_ns["node_name"];
				$current_route_code = $row_ns["current_route_code"];
			}
		}
	}
	else {
		$next_station_value = "---";
	}
	
	//--Final destinantion value
	$sql = 'select nn.node_name, pd.current_route_code from route_schedule_node_assoc rsna , node_names nn, persistent_data pd'
	        . ' WHERE'
	        . ' rsna.route_schedule_code = pd.current_route_code '
	        . ' AND rsna.node_code = nn.node_code'
	        . ' AND nn.lang_code = \''.$currentDriverLanguage.'\''
	        . ' ORDER BY rsna.node_seq_no DESC'
	        . ' LIMIT 1';
	if ( ($result_fd = query_wrapper($sql, __FILE__, __LINE__))==null){
		$error_occured = true;
	}
	else {
		if (mysql_num_rows($result_fd)==0){
			$sql = 'select nn.node_name, pd.current_route_code from route_schedule_node_assoc rsna , node_names nn, persistent_data pd'
			        . ' WHERE'
			        . ' rsna.route_schedule_code = pd.current_route_code '
			        . ' AND rsna.node_code = nn.node_code'
			        . ' AND nn.lang_code = \''.DEFAULT_LANG_FOR_DRIVER_INTERFACE.'\''
			        . ' ORDER BY rsna.node_seq_no DESC'
			        . ' LIMIT 1';
			if ( ($result_fd = query_wrapper($sql, __FILE__, __LINE__))==null){
				$error_occured = true;
			}
		}
	}

	if(!$error_occured){
		while ($row_fd = mysql_fetch_array($result_fd, MYSQL_ASSOC)) {
			$final_destination_value = $row_fd["node_name"];
			$current_route_code = $row_fd["current_route_code"];
		}
	}
	else {
		$final_destination_value = "---";
	}


	//--Current station value
	$currently_at_station = false;
	$sql = 'select current_node_code from persistent_data'
	        . ' LIMIT 1';
	if ( ($result = query_wrapper($sql, __FILE__, __LINE__))==null){
		$error_occured = true;
	}
	else {
		if (mysql_num_rows($result)> 0){//TODO...
			while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$current_station_code = trim($row["current_node_code"]);
			}
			if (strcmp($current_station_code,"")!=0){//means the vehicle is currently at a station
				$currently_at_station = true;
				$sql = 'select node_name from node_names'
				        . ' WHERE'
				        . ' node_code = \''.$current_station_code.'\''
						. ' AND lang_code = \''.$currentDriverLanguage.'\'';
						
				if ( ($result = query_wrapper($sql, __FILE__, __LINE__))==null){
					$error_occured = true;
				}
				else {
					if (mysql_num_rows($result)==0){
						$sql = 'select node_name from node_names'
						        . ' WHERE'
						        . ' node_code = \''.$current_station_code.'\''
								. ' AND lang_code = \''.DEFAULT_LANG_FOR_DRIVER_INTERFACE.'\'';
						if ( ($result = query_wrapper($sql, __FILE__, __LINE__))==null){
							$error_occured = true;
						}
					}
				}
			}
		}
	}

	if($currently_at_station && !$error_occured){
		while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
			$current_station_value = $row["node_name"];
		}
	}
	else {
		$current_station_value = "---";
	}

	
}

echo('<NextStation><name>'.$next_station_value.'</name><distance>'.$nextStationDistance.'</distance></NextStation>');
echo('<FinalDestination><name>'.$final_destination_value.'</name><distance>'.$finalDestinationDistance.'</distance></FinalDestination>');
if ($currently_at_station){
	echo('<CurrentStation><name>'.$current_station_value.'</name></CurrentStation>');
}
echo('<CurrentRouteCode>'.$current_route_code.'</CurrentRouteCode>');
echo ('<RouteChanged>'.(isCurrentRouteChanged()?'true':'false').'</RouteChanged>');
//Nearby places: Diatance query, in the range of 100 metres, for the POIs enroute - from the points_of_interest_descriptions table
//echo('<NearbyPlaces><place>'.'रूट बदलें'.'</place><place>'.'रूट बदलें'.'</place></NearbyPlaces>');
echo('</Document>');

function isCurrentRouteChanged(){

	$sql = "select current_route_code from persistent_data LIMIT 1";
	if ( ($result = query_wrapper($sql, __FILE__, __LINE__))==null){
		return false;
	}
	else {
		if ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
			if (strcmp($_SESSION['currentRoute'],$row["current_route_code"])==0)
				return false;
			else{
				$_SESSION['currentRoute'] = $row["current_route_code"];
				return true;
			}
		}
		else
			return false;
	}
}

?>